# user: oshrishm		id: 066583485

# Exercise 4 Question 3 - oddseries implementation

	.data	# Data declaration section
msg:	.asciiz "\nThe result is: "
newline:.asciiz "\n"
	.text
	.globl main
main:	
	li $v0, 5
	syscall
	
	# execute the oddseries function with the integer read from the user
	move $a0, $v0	
	jal oddseries
	
	move $s0, $v0		# save the pow result
	li $v0, 4		# set $v0 to print_string code
	la $a0, msg		# set $a0 to be msg
	syscall			# execute print_string
	li $v0, 1		# set $v0 to print_int code
	move $a0, $s0		# set $a0 to be the pow func.'s result
	syscall			# execute printf_int
	li $v0, 4		# set $v0 to print_string code
	la $a0, newline		# set $a0 to be newline
	syscall			# execute print_string
	
	li $v0, 10		# Syscall 10 - exit program
	syscall
	
# recieves 2 int args. a and b, returns a^b
pow:	
	addi $sp, $sp, -8
	sw $s0, 0($sp)
	sw $s1, 4($sp)

	move $s0, $a0
	move $s1, $a1
	move $v0, $zero
	
	beq $s0, $zero, pow_exit
	addi $v0, $v0, 1
	
	
loop:	
	beq $s1, $zero, pow_exit
	mul $v0, $v0, $s0
	addi $s1, $s1, -1
	j loop
pow_exit:
	lw $s0, 0($sp)
	lw $s1, 4($sp)
	addi $sp, 8
	jr $ra
	
	
# the oddseries function recievs an int arg - x and returns the oddseries sum of x
oddseries:
	# make room in the stack and save the regs. the function needs
	addi $sp, $sp, -20
	sw $s0, 0($sp)
	sw $s1, 4($sp)
	sw $s2, 8($sp)
	sw $s3, 12($sp)
	sw $ra, 16($sp)
	
	# assign working regs:
	move $s0, $a0				# assign x to $s0
	move $s2, $a0				# assign x to $s2 - this reg. is a constant in the function
	move $s3, $zero				# zero $s3 - this is the function's sum var.
	
	li $s1, 1				# $s1 is the index in the for loop	
for_test:					# for label - starts with checking 
	sle $t0, $s1, $s0			# 	if we iterated x times 
	beq $t0, $zero, exit_for
	
	# use pow to calc. i^(x-i)
	move $a0, $s1				
	move $a1, $s2
	jal pow
	# sum-up the returned value from pow
	add $s3, $s3, $v0
	
	# change var's value for next iteration
	addi $s1, $s1, 1
	addi $s2, $s2, -1
	j for_test

# from here the function wraps things up and returns to $ra
exit_for:
	move $v0, $s3
	
	lw $s0, 0($sp)
	lw $s1, 4($sp)
	lw $s2, 8($sp)
	lw $s3, 12($sp)
	lw $ra, 16($sp)
	addi $sp, $sp, 20
	jr $ra
	
# END OF PROGRAM